package Linux五种IO模型;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * @author coderFu
 * @create 2022/3/6
 * NIO 客户端模拟
 */
public class NioClient {

    // 同样的要素

    public static void main(String[] args) throws IOException {
        // 得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();

        //设置为非阻塞
        socketChannel.configureBlocking(false);

        // 提供IP 和端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress(9091);

        // 链接服务端
        if ( !socketChannel.connect(inetSocketAddress)){
            // 如果链接不上
            while (! socketChannel.finishConnect()){
                System.out.println("NIo 非阻塞");
            }
        }
        new Thread(new ClientTask(socketChannel)).start();
        // 不断检查是否有数据能够读取
        while (true){
            // 读取缓冲区的数据
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int count = socketChannel.write(byteBuffer);
            byte[] array = new byte[byteBuffer.position()];
            if (array.length >= 0){
                System.arraycopy(byteBuffer.array(),0,array,0,array.length);
                if (count > 0){
                    System.out.println(new String(array));
                }
            }
        }
    }


    static class  ClientTask implements Runnable{

        SocketChannel socketChannel;

        public ClientTask(SocketChannel socketChannel){
            this.socketChannel = socketChannel;
        }

        @Override
        public void run() {
            while (true){
                // 创建一个Buffer 对象并存入数据
                Scanner scanner = new Scanner(System.in);
                String m = scanner.nextLine();
                ByteBuffer buffer = ByteBuffer.wrap(m.getBytes());
                // 发送数据
                try{
                    socketChannel.write(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }




}
